from django.shortcuts import render
from rest_framework import status, mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from . import constants, serializers
from .models import User
from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, AddUserBrowsingHistorySerializer, SKUSerializer
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import UpdateModelMixin
from rest_framework.decorators import action
from django_redis import get_redis_connection
from goods.models import SKU
from rest_framework_jwt.views import ObtainJSONWebToken
from datetime import datetime
from carts.utils import merge_cart_cookie_to_redis



# Create your views here.

class UsernameCountView(APIView):
    """判断用户是否已注册"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        #包装响应数据
        data = {
            'username': username,
            'count': count
        }
        #响应
        return Response(data)

class MobileCountView(APIView):
    """判断手机号是否已注册"""
    def get(self, request, mobile):
        #查询数据库
        count = User.objects.filter(mobile=mobile).count()
        #构造响应数据
        data = {
            'mobile': mobile,
            'count': count
        }
        #响应
        return Response(data)

class UserView(CreateAPIView):
    """用户注册"""
    #指定序列化器
    serializer_class = CreateUserSerializer

#GET /user/
class UserDetailView(RetrieveAPIView):
    """用户详细信息展示"""
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]#指定权限，只有通过认证的用户才能访问当前视图

    def get_object(self):
        """重写此方法返回，要展示的用户模型对象"""
        return self.request.user

class EmailView(UpdateAPIView):
    """保存邮箱视图"""
    # 指定当前视图的权限(只有登录用户才能访问)
    permission_classes = [IsAuthenticated]
    # 指定序列化器
    serializer_class = EmailSerializer

    # 3.重写get_object(self)方法手动给它指定当前的登录用户
    def get_object(self):
        return self.request.user

class EmailVerifyView(APIView):
    """激活用户邮箱"""
    def get(self, request):
        #获取前端查询字符串中传入的token
        token = request.query_params.get('token')
        #把token解密 并查询对应的user
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        #验证token
        user = User.check_verify_email_token(token)
        #修改当前user的email_active为True
        if not user:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        #响应
        return Response({'message': 'OK'})

class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        #return super().create(request, *args, **kwargs) #等同于下面4句
        #创建序列化器进行反序列化
        serializer = self.get_serializer(data = request.data)
        #调用序列化器的is_valid()
        serializer.is_valid(raise_exception=True)
        #调用序列化器的save()
        serializer.save()
        #响应
        return Response(serializer.data, status=status.HTTP_201_CREATED)


    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id, #用户默认地址
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT, #用户地址数量
            'addresses': serializer.data, #用户地址数据
        })


    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

class UserBrowsingHistoryView(CreateAPIView):

    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """查询商品浏览记录"""

        #创建redis链接对象
        redis_conn = get_redis_connection('history')
        #获取当前请求的用户
        user = request.user
        #获取redis当前用户的浏览记录列表记录
        sku_ids = redis_conn.lrange('history_%d' % user.id, 0, -1)
        #把sku_id对应的sku模型查询出来
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)
        #创建序列化器进行序列化
        serializer = SKUSerializer(sku_list, many=True)
        #响应
        return Response(serializer.data)

jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER
class UserAuthorizeView(ObtainJSONWebToken):
    """自定义账号密码登录视图，实现购物车登录合并"""

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    response.data['token'],
                                    expires=expiration,
                                    httponly=True)
            #账号登录时合并购物车
            merge_cart_cookie_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)